package com.tree.commonutil.csv;

import com.opencsv.CSVReader;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
import com.tree.commonutil.TbUser;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CsvDemo1
 * @Description: map映射
 * @Author: myl
 * @Create_time:2021/5/7 14:05
 */
public class CsvDemo1 {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\document\\download-context\\bop副本.csv");
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", input);

        InputStreamReader inputStream = new InputStreamReader(multipartFile.getInputStream());
        // 设置解析策略，key-csv的头、value-DTO属性
        HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(TbUser.class);
        Map<String, String> columnMapping = new HashMap<>();

        // 关系映射
        columnMapping.put("Datetime", "dateTime");
        columnMapping.put("Value", "factorValue");
        strategy.setColumnMapping(columnMapping);

        CsvToBean csvToBean = new CsvToBeanBuilder(inputStream)
                .withMappingStrategy(strategy)
                .build();

        List carCsvDTOList = csvToBean.parse();

        carCsvDTOList.forEach(item -> System.out.println(item.toString()));
    }
}
